﻿using System;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;
using ToolUtil;
using zyconfig;

namespace zymain
{
    public partial class FrmRPhoto : Form
    {
        public DataTable dt;
        public FrmRPhoto()
        {
            InitializeComponent();
        }

        private void FrmRPhoto_Load(object sender, EventArgs e)
        {
            
        }

        private void FrmRPhoto_Shown(object sender, EventArgs e)
        {
            DataGridViewRow[] dtRows = new DataGridViewRow[this.dt.Rows.Count];
            for (int i = 0; i < this.dt.Rows.Count; i++)
            {
                dtRows[i] = new DataGridViewRow();
                dtRows[i].CreateCells(dataGridBook);
                dtRows[i].Cells[0].Value = this.dt.Rows[i]["读者条码"];
                dtRows[i].Cells[1].Value = this.dt.Rows[i]["借书证号"];
                dtRows[i].Cells[2].Value = this.dt.Rows[i]["姓名"];
            }
            dataGridBook.Rows.AddRange(dtRows);
            if (dataGridBook.Rows.Count > 0)
            {
                this.sxtBtn.Enabled = true;
                this.obdBtn.Enabled = true;
                this.owjBtn.Enabled = true;
                string dztm = dataGridBook.CurrentRow.Cells[0].Value.ToString();
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "读者条码='" + dztm + "'";
                    if (_open.GetField("读者库", "照片") != System.DBNull.Value)
                    {
                        Byte[] byteImageCol = (Byte[])(_open.GetField("读者库", "照片"));
                        MemoryStream stmImageCol = new MemoryStream(byteImageCol);
                        pictureBox1.Image = Image.FromStream(stmImageCol);
                    }
                    else
                    {
                        pictureBox1.Image = null;
                    }
                }
            }
            else
            {
                this.sxtBtn.Enabled = false;
                this.obdBtn.Enabled = false;
                this.owjBtn.Enabled = false;
            }
        }

        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            if (_selecting)
            {
                Pen pen = Pens.GreenYellow;
                e.Graphics.DrawRectangle(pen, _selection);
            }
        }
        private bool _selecting;
        private Rectangle _selection;
        //按下鼠标
        private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _selecting = true;
                _selection = new Rectangle(new System.Drawing.Point(e.X, e.Y), new System.Drawing.Size());
            }
            this.sviBtn.Enabled = false;
        }

        private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
        {
            if (_selecting)
            {
                _selection.Width = e.X - _selection.X;
                _selection.Height = e.Y - _selection.Y;
                // Redraw the picturebox:
                pictureBox2.Invalidate();
            }
        }
        private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
        {
            Bitmap bit = new Bitmap(pictureBox2.Width, pictureBox2.Height);//实例化一个和窗体一样大的bitmap
            Graphics g1 = Graphics.FromImage(bit);
            g1.CompositingQuality = CompositingQuality.HighQuality;//质量设为最高
            //g.CopyFromScreen(this.Left, this.Top, 0, 0, new Size(panel2.Width, panel2.Height));//保存整个窗体为图片
            g1.CopyFromScreen(pictureBox2.PointToScreen(System.Drawing.Point.Empty), System.Drawing.Point.Empty, pictureBox2.Size);
            if (e.Button == MouseButtons.Left && _selecting && _selection.Size != new System.Drawing.Size())
            {
                pictureBox1.Image = ImgTool.Cut(bit, _selection.X, _selection.Y, _selection.Width, _selection.Height);
                _selecting = false;
                this.sviBtn.Enabled = true;
            }
            else
            {
                _selecting = false;
                this.sviBtn.Enabled = false;
            }
        }

        private void dgb_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridViewRow row = this.dataGridBook.Rows[e.RowIndex];
                string dztm = row.Cells[0].Value.ToString();
                Console.WriteLine(dztm);
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "读者条码='" + dztm + "'";
                    if (_open.GetField("读者库", "照片") != System.DBNull.Value)
                    {
                        Byte[] byteImageCol = (Byte[])(_open.GetField("读者库", "照片"));
                        MemoryStream stmImageCol = new MemoryStream(byteImageCol);
                        pictureBox1.Image = Image.FromStream(stmImageCol);
                    }
                    else
                    {
                        pictureBox1.Image = null;
                    }
                }
            }
        }

        private void sxtBtn_Click(object sender, EventArgs e)
        {
            FrmVideo f = new FrmVideo();
            if(f.ShowDialog() == DialogResult.OK)
            {
                this.pictureBox2.Image = f.pictureBox1.Image;
                this.lddBtn.Enabled = true;
                this.lduBtn.Enabled = true;
                this.izxBtn.Enabled = true;
                this.iyxBtn.Enabled = true;
            }
            else
            {
                this.lddBtn.Enabled = false;
                this.lduBtn.Enabled = false;
                this.izxBtn.Enabled = false;
                this.iyxBtn.Enabled = false;
            }
        }
        private int changeValue = 5;
        private void lddBtn_Click(object sender, EventArgs e)
        {
            Bitmap picture = new Bitmap(pictureBox2.Image);
            for (short x = 0; x < picture.Width; x++)
            {
                for (short y = 0; y < picture.Height; y++)
                {
                    Color pixColor = picture.GetPixel(x, y);
                    byte R, G, B;
                    R = (0 < pixColor.R - changeValue && pixColor.R - changeValue < 255) ? (byte)(pixColor.R + changeValue) : pixColor.R;
                    G = (0 < pixColor.G - changeValue && pixColor.G - changeValue < 255) ? (byte)(pixColor.G + changeValue) : pixColor.G;
                    B = (0 < pixColor.B - changeValue && pixColor.B - changeValue < 255) ? (byte)(pixColor.B + changeValue) : pixColor.B;
                    Color newPixColor = Color.FromArgb(R, G, B);
                    picture.SetPixel(x, y, newPixColor);
                }
            }
            pictureBox2.Image = picture;
        }

        private void lduBtn_Click(object sender, EventArgs e)
        {
            Bitmap picture = new Bitmap(pictureBox2.Image);
            for (short x = 0; x < picture.Width; x++)
            {
                for (short y = 0; y < picture.Height; y++)
                {
                    Color pixColor = picture.GetPixel(x, y);
                    byte R, G, B;
                    R = (0 < pixColor.R + changeValue && pixColor.R + changeValue < 255) ? (byte)(pixColor.R + changeValue) : pixColor.R;
                    G = (0 < pixColor.G + changeValue && pixColor.G + changeValue < 255) ? (byte)(pixColor.G + changeValue) : pixColor.G;
                    B = (0 < pixColor.B + changeValue && pixColor.B + changeValue < 255) ? (byte)(pixColor.B + changeValue) : pixColor.B;
                    Color newPixColor = Color.FromArgb(R, G, B);
                    picture.SetPixel(x, y, newPixColor);
                }
            }
            pictureBox2.Image = picture;
        }
        /// <summary>
        /// 向左旋转90
        /// </summary>
        private void izxBtn_Click(object sender, EventArgs e)
        {
            if (this.pictureBox2.Image == null)
                return;
            Bitmap img = new Bitmap(this.pictureBox2.Image);
            if (img != null)
            {
                img.RotateFlip(RotateFlipType.Rotate90FlipXY);
                pictureBox2.Image = img;
            }

        }
        private void izxBtn1_Click(object sender, EventArgs e)
        {
            if (this.pictureBox2.Image == null)
                return;
            Bitmap img = new Bitmap(this.pictureBox2.Image);
            double angle = 45.0;
            angle = angle % 360;
            //弧度转换 
            double radian = angle * Math.PI / 180.0;
            double cos = Math.Cos(radian);
            double sin = Math.Sin(radian);
            //原图的宽和高 
            int w = img.Width;
            int h = img.Height;
            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
            //目标位图 
            Bitmap dsImage = new Bitmap(W, H);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //计算偏移量 
            System.Drawing.Point Offset = new System.Drawing.Point((W - w) / 2, (H - h) / 2);
            //构造图像显示区域:让图像的中心与窗口的中心点一致 
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(Offset.X, Offset.Y, w, h);
            System.Drawing.Point center = new System.Drawing.Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
            g.TranslateTransform(center.X, center.Y);
            g.RotateTransform((float)angle);
            //恢复图像在水平和垂直方向的平移 
            g.TranslateTransform(-center.X, -center.Y);
            g.DrawImage(img, rect);
            //重至绘图的所有变换 
            g.ResetTransform();
            g.Save();
            g.Dispose();

            this.pictureBox2.Image = dsImage;
        }

        private void obdBtn_Click(object sender, EventArgs e)
        {
            // 打开图像文件
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "图片|*.bmp;*.jpg;*.jpeg;*.png";

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                Bitmap SourceBitmap = new Bitmap(openFile.FileName);
                Bitmap UsedMap = new Bitmap(SourceBitmap, this.pictureBox2.Width, this.pictureBox2.Height);
                pictureBox2.Image = UsedMap;
                this.lddBtn.Enabled = true;
                this.lduBtn.Enabled = true;
                this.izxBtn.Enabled = true;
                this.iyxBtn.Enabled = true;
            }
            else
            {
                this.lddBtn.Enabled = false;
                this.lduBtn.Enabled = false;
                this.izxBtn.Enabled = false;
                this.iyxBtn.Enabled = false;
            }
        }
        /// <summary>
        /// 向右旋转 270
        /// </summary>
        private void iyxBtn_Click(object sender, EventArgs e)
        {
            if (this.pictureBox2.Image == null)
                return;
            Bitmap img = new Bitmap(this.pictureBox2.Image);
            if (img != null)
            {
                img.RotateFlip(RotateFlipType.Rotate270FlipXY);
                pictureBox2.Image = img;
            }
        }

        // 以图像高度的中垂线为对称轴，上下对换
        private void InverseVer_Click(object sender, EventArgs e)
        {
            if (this.pictureBox2.Image == null)
                return;
            Bitmap image = new Bitmap(this.pictureBox2.Image);
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, image.Width, image.Height);
            BitmapData bmpData = image.LockBits(rect, ImageLockMode.ReadWrite, image.PixelFormat);
            IntPtr ptr = bmpData.Scan0;
            int bytes = 0;
            if (image.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                bytes = image.Width * image.Height * 4;
            }
            byte[] pixels = new byte[bytes];
            Marshal.Copy(ptr, pixels, 0, bytes);
            byte temp1;
            byte temp2;
            byte temp3;
            byte temp4;
            for (int i = 0; i < image.Width; i++)
            {
                for (int j = 0; j < image.Height / 2; j++)
                {
                    temp1 = pixels[0 + j * image.Width * 4 + i * 4];
                    temp2 = pixels[1 + j * image.Width * 4 + i * 4];
                    temp3 = pixels[2 + j * image.Width * 4 + i * 4];
                    temp4 = pixels[3 + j * image.Width * 4 + i * 4];
                    pixels[0 + j * image.Width * 4 + i * 4] = pixels[0 + (image.Height - 1 - j) * image.Width * 4 + i * 4];
                    pixels[1 + j * image.Width * 4 + i * 4] = pixels[1 + (image.Height - 1 - j) * image.Width * 4 + i * 4];
                    pixels[2 + j * image.Width * 4 + i * 4] = pixels[2 + (image.Height - 1 - j) * image.Width * 4 + i * 4];
                    pixels[3 + j * image.Width * 4 + i * 4] = pixels[3 + (image.Height - 1 - j) * image.Width * 4 + i * 4];
                    pixels[0 + (image.Height - 1 - j) * image.Width * 4 + i * 4] = temp1;
                    pixels[1 + (image.Height - 1 - j) * image.Width * 4 + i * 4] = temp2;
                    pixels[2 + (image.Height - 1 - j) * image.Width * 4 + i * 4] = temp3;
                    pixels[3 + (image.Height - 1 - j) * image.Width * 4 + i * 4] = temp4;
                }
            }
            Marshal.Copy(pixels, 0, ptr, bytes);
            // 从系统中解锁
            image.UnlockBits(bmpData);
            this.pictureBox2.Image = image;
        }

        // 以图像宽度的中垂线为对称轴，左右对换
        private void Inverse_Click(object sender, EventArgs e)
        {
            if (this.pictureBox2.Image == null)
                return;
            Bitmap inverseImage = new Bitmap(this.pictureBox2.Image);
            // 用指定的位置和大小初始化System.Drawing.Rectangle类的新实例矩形
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, inverseImage.Width, inverseImage.Height);
            // 将UsedMap锁定到系统内存中
            BitmapData bmpData = inverseImage.LockBits(rect, ImageLockMode.ReadWrite, inverseImage.PixelFormat);

            // 获取位图中第一个像素数据的地址
            IntPtr ptr = bmpData.Scan0;
            int bytes = 0;
            if (inverseImage.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
            {
                bytes = inverseImage.Width * inverseImage.Height;
            }
            if (inverseImage.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
            {
                bytes = inverseImage.Width * inverseImage.Height * 3;
            }
            // 指定格式为每像素 32 位；alpha、红色、绿色和蓝色分量各使用 8 位。
            if (inverseImage.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                bytes = inverseImage.Width * inverseImage.Height * 4;
            }
            byte[] pixelValues = new byte[bytes];
            // 将数据从非托管内存指针复制到托管8位无符号整数数组
            Marshal.Copy(ptr, pixelValues, 0, bytes);
            // 竖直中轴
            int halfWidth = inverseImage.Width / 2;
            byte temp;
            byte temp1;
            byte temp2;
            byte temp3;
            if (inverseImage.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                for (int r = 0; r < inverseImage.Height; r++)
                    for (int c = 0; c < halfWidth; c++)
                    {
                        temp = pixelValues[0 + r * inverseImage.Width * 4 + c * 4];
                        temp1 = pixelValues[1 + r * inverseImage.Width * 4 + c * 4];
                        temp2 = pixelValues[2 + r * inverseImage.Width * 4 + c * 4];
                        temp3 = pixelValues[3 + r * inverseImage.Width * 4 + c * 4];
                        pixelValues[0 + r * inverseImage.Width * 4 + c * 4] = pixelValues[0 + (r + 1) * inverseImage.Width * 4 - (c + 1) * 4];
                        pixelValues[1 + r * inverseImage.Width * 4 + c * 4] = pixelValues[1 + (r + 1) * inverseImage.Width * 4 - (c + 1) * 4];
                        pixelValues[2 + r * inverseImage.Width * 4 + c * 4] = pixelValues[2 + (r + 1) * inverseImage.Width * 4 - (c + 1) * 4];
                        pixelValues[3 + r * inverseImage.Width * 4 + c * 4] = pixelValues[3 + (r + 1) * inverseImage.Width * 4 - (c + 1) * 4];
                        pixelValues[0 + (r + 1) * inverseImage.Width * 4 - (c + 1) * 4] = temp;
                        pixelValues[1 + (r + 1) * inverseImage.Width * 4 - (c + 1) * 4] = temp1;
                        pixelValues[2 + (r + 1) * inverseImage.Width * 4 - (c + 1) * 4] = temp2;
                        pixelValues[3 + (r + 1) * inverseImage.Width * 4 - (c + 1) * 4] = temp3;
                    }
            }
            Marshal.Copy(pixelValues, 0, ptr, bytes);
            // 从系统中解锁
            inverseImage.UnlockBits(bmpData);
            this.pictureBox2.Image = inverseImage;
        }
    }
}
